/*=============================================================================
#    The element-comm is a tentative program used to test our ideas.           
#                       Copyright (C)  bgao                                    
#
#     This program is free software; you can redistribute it and/or            
#      modify it under the terms of the GNU General Public License             
#     as published by the Free Software Foundation; either version 2           
#         of the License, or (at your option) any later version.               
#
#     This program is distributed in the hope that it will be useful,          
#    but WITHOUT ANY WARRANTY; without even the implied warranty of           
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the            
#             GNU General Public License for more details.                    
#
#    You should have received a copy of the GNU General Public License        
#     along with this program; if not, write to the Free Software             
#      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,             
#                       MA  02110-1301, USA.                                  
#==============================================================================
# $Id: mem.c 348 2010-11-29 09:01:16Z bgao $ 
#
# $Author: bgao $ 
#
# $Revision: 348 $ 
#
# $Date: 2010-11-29 17:01:16 +0800 (星期一, 29 十一月 2010) $ 
#
# Description: 
#
=============================================================================*/
/*! @file mem.c
 *  @brief This file defines the memory management module,
 *         which is a base library used by other modules.
 */
#include "mem.h"

/*! initialize the mem's free list.
 *  @param list pointer to the free_list.
 *  @param pool pointer to the structure of pool.
 *  @return -1 if pool structure is NULL or the pool is
 *          NULL or the available memory block is NULL
 *          else return 0.
 */
int8 mem_init(free_list list, pool_t *pool)
{
    list_item_t *v;
    int i;

    if (pool == NULL || pool->ptr == NULL || pool->num == 0)
        return MEM_ERR;

    v = *list = pool->ptr;

    for(i = 0; i < (pool->num-1); i++) {
        pool->ptr += pool->size;
        v->next = pool->ptr;
        v = v->next;
    }

    v->next = NULL;

    return MEM_OK;
}

/* allocate a memory from the free list.
 * @param list pointer to the free list.
 * @return the pointer to the allocated memory block.
 */
void *mem_alloc(free_list list)
{
    return list_del_head(list);
}

/* give back the allocated memory to the free list.
 * @param list pointer to the free list.
 * @block block pointer to the memory block to be freed.
 * @return -1 if the block is NULL else return 0.
 */
int8 mem_free(free_list list, void *block)
{
    return list_add_head(list, block);
}

